import React from 'react'
import  { useEffect,  useState } from 'react'
import {Table,Button,Modal,notification} from 'antd'
import { useNavigate} from 'react-router-dom';
import {EditOutlined,DeleteOutlined,VerticalAlignTopOutlined,ExclamationCircleOutlined} from '@ant-design/icons'
import axios from 'axios'
const { confirm } = Modal;

export default function NewsDraft(props) {
  const navigate=useNavigate()
  const[dataSource,setDataSource]=useState([])

const {username}=JSON.parse(localStorage.getItem('token'))
  useEffect(()=>{
    axios.get(`http://localhost:8000/news?author=${username}&auditState=0&_expand=category`).then(res=>{
      // ?author=${username}&auditState=0&_expand=category
        const list=res.data
        // console.log('list:',list);
         setDataSource(list)
    })
  },[username])

const handleCheck=(id)=>{
  axios.patch(`http://localhost:8000/news/${id}`,{
    "auditState":1,//0草稿箱，1待审核，2审核通过，3审核被拒绝
  }).then(res=>{
    navigate('/audit-manage/list');
    // props.history.push(auditState===0?'/news-manage/draft':'/audit-manage/list');
    notification.info({
      message: `通知`,
      description:
        `您可以到审核列表中查看您的新闻`,
      placement:'bottomRight',
    });
  })
}
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      render:(id)=> {
        return <b>{id}</b>
      },
    },
    {
      title: '新闻标题',
      dataIndex: 'title',
      render:(title,item)=>{
        return<a href={`/news-manage/preview/${item.id}`}>{title}</a>
      }
    },
    {
      title: '作者',
      dataIndex: 'author',
    },
    {
      title: '新闻分类',
      dataIndex: 'categoryId',
      render:(categoryId)=>{
        return <b>{categoryId}</b>
    }
    },
    {
      title: '操作',
      render:(item)=>{
        return <div>
            <Button danger shape="circle"  onClick={()=>showDeleteConfirm(item) }  icon={<DeleteOutlined />}/>
            <Button  shape="circle" icon={<EditOutlined />} disabled={item.default}  
            onClick={()=>{
              window.location.href=`/news-manage/update/${item.id}`
            }}
            />
            <Button type="primary" shape="circle"  icon={<VerticalAlignTopOutlined />} onClick={()=>handleCheck(item.id)}/>
        </div>  
      }
    },
  ];
    
  const showDeleteConfirm = (item) => {
    confirm({
      title: '你确认要删除吗?',
      icon: <ExclamationCircleOutlined />,
      // content: 'Some descriptions',
      okType: 'danger',
      okText: '确认',
      cancelText: '取消',
      onOk() {
       deleteMethod(item)
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  const deleteMethod=(item)=>{
    setDataSource(dataSource.filter(data=>data.id!==item.id))   
    console.log('item',item)
    // 有个小问题，不知道为什么删除会把所有东西删掉
    // axios.delete(`http://localhost:8000/news/${item.id}`)
  }
  

  return (
  <div>
   <Table dataSource={dataSource} columns={columns} pagination={{ pageSize:5}} rowKey={item=>item.id}/>
 </div>
  )
}
